package com.yitiao.socket.chatroom.aio;

import com.yitiao.socket.chatroom.CommonConst;
import com.yitiao.socket.chatroom.demo.ClientHandler;
import lombok.SneakyThrows;

import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.util.HashMap;
import java.util.Map;

public class AcceptChatHandler implements CompletionHandler<AsynchronousSocketChannel,ByteBuffer> {

    private AioChatServer server;

    public AcceptChatHandler(AioChatServer server) {
        this.server = server;
    }

    @SneakyThrows
    @Override
    public void completed(AsynchronousSocketChannel result, ByteBuffer attachment) {
        if (result.isOpen()){
            ClientChatHandler clientHandler = new ClientChatHandler(result,server);
            server.addClient(clientHandler);
            ByteBuffer buffer = ByteBuffer.allocate(CommonConst.BUFFER);
            Map<String, Object> info = new HashMap<>();
            info.put("type", "read");
            info.put("buffer", buffer);
            result.read(buffer,buffer,clientHandler);
        }
    }

    @Override
    public void failed(Throwable exc, ByteBuffer attachment) {

    }
}
